import Vue from 'vue'
import VueRouter from 'vue-router'
import UserLayout from '@/layouts/UserLayout'
import { getRouter,generator } from './generator-routers'
import { findNodeInTree } from '@/utils/util'

import store from '../store/index'

// import NProgress from 'nprogress' // progress bar
// import '@/components/NProgress/nprogress.less' // progress bar custom style
// import store from '../router'
import storage from 'store'

Vue.use(VueRouter)

var routes = [
  {
    path: '/user',
    component: UserLayout,
    redirect: '/user/login',
    children: [
      {
        path: '/login',
        name: 'login',
        component: () => import('@/views/user/login'),
      },
    ], 
  },
  {
    path: '/404',
    component: () => import('@/views/exception/404'),
  },
]
// NProgress.configure({ showSpinner: true })
const dynamicRouters = getRouter()
routes = [...routes, ...dynamicRouters]
const router = new VueRouter({
  mode: 'hash',
  base: process.env.BASE_URL,
  routes,
})
const loginRoutePath = '/login'
const defaultRoutePath = '/'



router.beforeEach(async (to, from, next) => {
  // NProgress.start() // start progress bar
  const token = storage.get('token')
  if(token) {
    if (to.path === loginRoutePath) {
      next({ path: defaultRoutePath })
    }else {
      const menuList = store.state.menuList && store.state.menuList.length > 0
      if(menuList) {
        let treeData = {
          value: -1,
          children: store.state.menuList
        }
        // 判断是否有该路由权限
        const isAuth = findNodeInTree(treeData,to.path,null,'path')
        if(to.path === '/404') {
         next()
        }else {
          if(isAuth) {
            next()
          }else {
            next({path: '/404'})
          }
        }
      }else {
        try {
          await store.dispatch('getUsersInfo')
          await store.dispatch('getUsersMenu')
          next({ ...to, replace: true })
        } catch (error) {
          next(`/login?redirect=${to.path}`)
        }
      }
    }
  }else {
     /* has no token*/
     if (to.path === loginRoutePath) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
    }
  }
})

router.afterEach(() => {
  // NProgress.done() // finish progress bar
})


export default router
